package controller;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;


import model.Block;
import model.Bob;
import model.Bullet;
import model.Bullet.State;
import model.World;

public class FireController {
	World world;
	WorldController worldControl;
	Bob bob;
	Sound[] bulletSound;
	public FireController(WorldController worldControl){
		this.worldControl=worldControl;
		this.world = worldControl.getBobControl().getWorld();
		this.bob = world.getBob();
		initSound();
	}
	private void initSound(){
		bulletSound=new Sound[3];
		bulletSound[0]=	Gdx.audio.newSound(Gdx.files.internal("sound/bulletcollisblock.mp3"));
	}
	public void update(float delta){
		for(Bullet bullet : bob.getFire()){
			if(checkCollistionWithBlock(bullet)){
				bullet.setState(State.COLLISTED);
				bulletSound[0].play();
				bullet.setVelocity(new Vector2(0,0));
			}
		}
	}
	public boolean checkCollistionWithBlock(Bullet bullet){
		int startX, startY, endX,endY;
		Rectangle bulletRect = new Rectangle();
		bulletRect.x=bullet.getPosition().x;
		bulletRect.y=bullet.getPosition().y;
		bulletRect.width = bullet.getBound().width;
		bulletRect.height = bullet.getBound().height;
		startY=(int)bullet.getBound().y;
		endY=(int)(bullet.getBound().y+bob.getBounds().height);
		if(bullet.getVelocity().x<0){
			endX=(int)Math.floor(bullet.getBound().x);
			startX=(int)Math.floor(bullet.getBound().x +bullet.getVelocity().x);
		}
		else {
			startX=(int)Math.floor(bullet.getBound().x+bullet.getBound().width);
			endX=(int)Math.floor(bullet.getBound().x+bullet.getBound().width+bullet.getVelocity().x);
		}
		Array<Block> collidable=worldControl.populateCollidableBlocks(startX, startY, endX, endY);
	
		for(Block block: collidable){
			if(block==null)continue;
			if(bulletRect.overlaps(block.getBounds())){
				return true;
			}
		}
		return false;
		
	}
}
